require "Net/send_Msg"
require 'View/UIBase/UIBase'

UIPetFriendList = UIBase.New(PanelNames.UIPetFriendList);
local pagePetIdx = 0;--当前页面开头的宠物索引
local callBack = nil;
local this = UIPetFriendList

function UIPetFriendList.Init(func)
    UIBase.Init(UIPetFriendList, func);
    callBack = func;

end

--定义控件
function UIPetFriendList:OnCreate()
    self.friendList = self:GetChild("list"):GetChild("list")
    self.backBtn = self:GetChild("btnBack")
    self.bgClose = self:GetChild("bgClose")
    self.pageNumText = self:GetChild("numPage")
    self.lastBtn = self:GetChild("btnPrevious")
    self.nextBtn = self:GetChild("btnNext")
    self.friendList.itemRenderer = self.rendererItem
    self.petListModelInfo = {}
    self.friendListInfo = {}
    self.curPageIndex = nil
    friendHandler.ReqFriendData()
    self:refreshPanel()
end

function UIPetFriendList:refreshPanel()
    local infos = FriendManager.GetFriendList(EnumConst.FriendType.myFriend)
    self.friendListInfo = {}
    for k, v in pairs(infos) do
        if v.petInfo ~= nil then
            table.insert(self.friendListInfo, v)
        end
    end
    
    self.curPageIndex = self.curPageIndex or 1 
    if self.curPageIndex <= 0 then self.curPageIndex = 1 end
    self.allPage = math.ceil( #self.friendListInfo/ 9)
    if self.curPageIndex > self.allPage then 
        self.curPageIndex = self.allPage
    end
 
    self.pageNumText.text = self.curPageIndex .. "/" .. self.allPage
 
    if self.curPageIndex <= 1 then 
        self.lastBtn.visible = false 
    else
        self.lastBtn.visible = true
    end
    if self.curPageIndex >= self.allPage then 
        self.nextBtn.visible = false 
    else
        self.nextBtn.visible = true
    end
    self.times = {}

    if #self.friendListInfo == 0 then 
        self.friendList.numItems = 0
        return 
    end

    local num = 0
    if self.curPageIndex * 9 > #self.friendListInfo then
        num = #self.friendListInfo - (self.curPageIndex-1) * 9
    else
        num = 9
    end
    self.friendList.numItems = num
     
end

function UIPetFriendList:OnEnable()
    self:refreshPanel()
    self:addEvent()
    self:updateTimer()
end

function UIPetFriendList:OnDisable()
    self:removeEvent()
end

function UIPetFriendList:OnDestroy()

end

function UIPetFriendList:addEvent()
    self:RegisterEvent(Config.EventType.Fresh_MyFriends,self.refreshPanel,self)
    self:RegisterEvent(Config.EventType.Fresh_MyFriendPetInfo, self.refreshPanel, self);
    self:RegisterOnClick(self.nextBtn, self.nextPage, self)
    self:RegisterOnClick(self.lastBtn, self.lastPage, self)

    self.backBtn.onClick:Add(self.onCloseClick);
    self.bgClose.onClick:Add(self.onCloseClick);

end

function UIPetFriendList:removeEvent()
    self.backBtn.onClick:Clear();
    self.bgClose.onClick:Clear();
    self:UnRegisterEvent(Config.EventType.Fresh_MyFriendPetInfo, self.refreshPanel, self);
    self:UnRegisterEvent(Config.EventType.Fresh_MyFriends, self.refreshPanel, self);
    if self.petTimer then
        utimer.remove(self.petTimer)
        self.petTimer = nil
    end
end

function UIPetFriendList.rendererItem(index, obj) 
    local page = (this.curPageIndex-1)*9
    if page < 0 then page =0 end
    local info = this.friendListInfo[ page + index + 1];
    local petInfo = info.petInfo;
    local name = obj:GetChild("playerName");
    local petName = obj:GetChild("PetName");
    local nodePet = obj:GetChild("Model_Pet");
    local head = obj:GetChild("head")
    local timeText = obj:GetChild("Txt_MatingEndTime");
    obj.onClick:Clear();
    local callFunc = function()
        local data = {};
        data.data = {};
        data.data.pet = {};
        data.data.pet[1] = petInfo;
        data.data.playerId = info.playerId;
        data.data.name = info.name;
        data.data.pic = info.pic;
        data.data.picFrame = info.picFrame;
        this:onClickPetMating(data)
    end
    local _matingEndTime = tonumber(tostring(petInfo.matingEndTime));
    local timeController = obj:GetController("timeShow");
    local _lastMatingEndTime = ""
    if (table.getn(PetManager.myApply) == 0 or (PetManager.myApply.templatePetInfo and PetManager.myApply.templatePetInfo.petId ~= petInfo.petId)) and _matingEndTime / 1000 - HelperFunc.GetServerTime() <= 0 then
        timeController.selectedIndex = 0;
    elseif _matingEndTime / 1000 - HelperFunc.GetServerTime() > 0 then
        timeController.selectedIndex = 2;
        this.times[index] = math.floor(_matingEndTime / 1000);
        _lastMatingEndTime = TimeFormatToHHMMSS(_matingEndTime / 1000 - HelperFunc.GetServerTime())
        timeText.text = _lastMatingEndTime;
        callFunc = function()
            UISysTips.AddMsg(getLanguage("PetApply_weak"))
        end
    else
        timeController.selectedIndex = 1;
        this.times[index] = PetManager.myApply.endTime
        _lastMatingEndTime = TimeFormatToHHMMSS(PetManager.myApply.endTime - HelperFunc.GetServerTime())
        timeText.text = _lastMatingEndTime;
    end
    obj.onClick:Add(callFunc)
    petName.text = PetManager.GetPetName(this.genes)
    name.text = info.name;
    head:GetChild("head"):GetChild("HeadIcon").url = "ui://ICONAtlas/" .. logicMgr.HeroManager.GetHeroConfigbyModelId(tonumber(info.pic)).f_HeroIcon;
    head:GetChild("frame").url = "ui://ICONAtlas/" .. info.picFrame;
    if this.petListModelInfo[index + 1] == nil then
        this.petListModelInfo[index + 1] = {}
    end
    if this.petListModelInfo[index + 1].modelGO and this.petListModelInfo[index + 1].petId == petInfo.petId then
        PetManager.PetModelRefresh(this.petListModelInfo[index + 1], petInfo.genes, false)
    else
        this:removePetListModelByIndex(index + 1)
        resMgr:LoadModelPrefab(PetManager.PetModelPrefab, function(go)
            this.petListModelInfo[index + 1].modelGO = newObject(go)
            this.petListModelInfo[index + 1].parentGO = nodePet
            local _modelWrapper = this.petListModelInfo[index + 1].modelWrapper
            this.petListModelInfo[index + 1].modelWrapper = GoWrapper.New()
            this.petListModelInfo[index + 1].petId = petInfo.petId
            PetManager.PetModelFirstSet(this.petListModelInfo[index + 1], petInfo.genes, false, Vector3.New(0, 0, 0), Vector3.New(1.2, 1.2, 1))
            if _modelWrapper then
                _modelWrapper:Dispose()
            end
        end)
    end

end

function UIPetFriendList:onClickPetMating(info)
    PetManager.refreshOtherPetInfo(info)
    if PetManager.OtherPetInfo and table.getn(PetManager.OtherPetInfo) > 0 then
        if #PetManager.PetInfoList == 0 then
            UISysTips.AddMsg(getLanguage("PetMating_DoNotHaveAnyPet"))
        elseif table.getn(PetManager.myApply) > 0 and PetManager.OtherPetInfo.petId ~= PetManager.myApply.templatePetInfo.petId then
            UISysTips.AddMsg(getLanguage("PetMating_CannotMultipleApply"))
        else
            showUI(PanelNames.Page_PetApplyMyRequest)
        end
    else
        UISysTips.AddMsg(getLanguage("PetMating_CurrentPlayerNoPet"))
    end
end

function UIPetFriendList:removePetListModelByIndex(index)
    if self.petListModelInfo[index].modelGO then
        destroyImmediate(self.petListModelInfo[index].modelGO)
    end
    self.petListModelInfo[index].modelGO = nil
    self.petListModelInfo[index].parentGO = nil
    self.petListModelInfo[index].petId = nil
end

function UIPetFriendList:lastPage()
    self.curPageIndex = self.curPageIndex - 1;
    if self.curPageIndex <= 1 then
        self.lastBtn.visible = false 
    end
    if self.curPageIndex < self.allPage then
        self.nextBtn.visible = true;
    end
    self.times = {};
    self.friendList.numItems = 9
    -- self:updateTimer()
    self.pageNumText.text = self.curPageIndex  .. "/" .. self.allPage;

end

function UIPetFriendList:nextPage()
    self.curPageIndex = self.curPageIndex + 1;
    if self.curPageIndex > 1 then
        self.lastBtn.visible = true;
    end
    if self.curPageIndex >= self.allPage then
        self.nextBtn.visible = false;
    end
 
    local num = 0
    if self.curPageIndex * 9 > #self.friendListInfo then
        num = #self.friendListInfo - (self.curPageIndex-1) * 9
    else
        num = 9
    end  
    self.times = {};
    self.friendList.numItems = num;
    -- self:updateTimer()
    self.pageNumText.text = self.curPageIndex  .. "/" .. self.allPage;
end

function UIPetFriendList.onCloseClick()
    closeUI(PanelNames.UIPetFriendList);
    if callBack then
        callBack()
        callBack = nil;
    end
end

function UIPetFriendList:updateTimer()
    if self.petTimer then
        utimer.remove(self.petTimer)
        self.petTimer = nil
    end 
    self.petTimer = utimer.timeCall(function()
        for k, v in pairs(self.times) do
            self.times[k] = self.times[k] - 1
            local timeCd = self.times[k] - HelperFunc.GetServerTime();
            local item = self.friendList:GetChildAt(k);
            local timeText = item:GetChild("Txt_MatingEndTime")
            timeText.text = TimeFormatToHHMMSS(timeCd)
            if timeCd <= 0 then
                self.times[k] = nil;
                if table.getn(self.times) <= 0 then
                    UIPetFriendList:refreshPanel() 
                end
            end
        end
    end, 1000, -1)
end

return UIPetFriendList;